/**  
* @Title: GlobalInterceptor.java <br>
* @Package com.xzit.ar.common.interceptor <br>
* @Description: TODO <br>
* @author Mr.Black <br>
* @date 2016年1月2日 下午5:25:54 <br>
* @version V1.0 <br>
*/
package com.xzit.tmms.common.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.xzit.tmms.common.constant.WebConstant;
import com.xzit.tmms.common.util.CommonUtil;
import com.xzit.tmms.common.util.privilege.PrivilegeUtil;

/**
 * @ClassName: GlobalInterceptor <br>
 * @Description: TODO 登录拦截<br>
 * @author Mr.Black <br>
 * @date 2016年1月2日 下午5:25:54 <br>
 * @version V1.0 <br>
 */
public class GlobalInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		// 获取请求URL
		String uri = request.getRequestURI();
		String queryString = request.getQueryString();
		// 全限定名判断
		if (uri.indexOf("/tmms") > -1) {
			uri = uri.substring(uri.indexOf("/", uri.indexOf("/tmms") + 1), uri.indexOf(".action"));
			System.out.println(uri);
		}
		// 判断公开资源
		if (uri.contains("login") || PrivilegeUtil.isPublic(uri)) {
			// 公开资源， 放行
			return true;
		}

		// 获取 session, 取出登录信息
		HttpSession session = request.getSession();
		// 管理员登录
		@SuppressWarnings("rawtypes")
		Map user = (Map) session.getAttribute(WebConstant.SESSION_USER);
		// 获取用户信息
		if (user != null && CommonUtil.isNotEmpty((String) user.get("account"))) {
			// 登录标识位校验
			String loginFlag = (String) session.getAttribute(WebConstant.SESSION_LOGIN_FLAG);
			if (loginFlag.equals(WebConstant.SESSION_LOGIN_FLAG)) {
				// 已登录，校验权限
				// 超级管理员
				if (user.get("superAdmin") != null && user.get("superAdmin").toString().equals("1")) {
					return true;
				} else {
					// 权限校验
					long[] rights = (long[]) user.get("rights");
					if (PrivilegeUtil.hasRight(uri, rights)) {
						return true;
					} else {
						response.sendRedirect(request.getScheme() + "://" + request.getServerName() + ":"
								+ request.getServerPort() + request.getContextPath() + "/noRight.action");
						return false;
					}
				}
			}
		}
		// session中没有登录信息, 跳转登录界面
		response.sendRedirect(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getContextPath() + "/login.action?queryString=" + uri + ".action?" + queryString);

		return true;
	}

}
